package com.atguigu.gmall.auth.config;

import com.atguigu.gmall.common.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;


import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@ConfigurationProperties(prefix = "jwt")
@Data
@Slf4j
public class JwtProperties {
    private String pubKeyPath;
    private String priKeyPath;
    private String secret;
    private String cookieName;
    private Integer expire;
    private String unick;

    //公钥对象
    private PublicKey publicKey;
    //私钥对象
    private PrivateKey privateKey;



    //在构造方法执行之后执行 为公钥对象与私钥对象赋值
    @PostConstruct
    public void init(){

        try {
            //获取公钥与私钥文件
            File pubFile = new File(pubKeyPath);
            File priFile = new File(priKeyPath);

            //如果公钥文件与私钥文件不存在 重新生成文件
            if (!pubFile.exists() || !priFile.exists()) {
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            //赋值
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("生成公钥和私钥出错!");
            e.printStackTrace();
        }
    }
}
